import { apiClient } from './apiClient';

// LLM 相关接口
export interface LLMModel {
  id: number;
  name: string;
  provider: string;
  llm_model_id: string;
  max_tokens: number;
  temperature: number;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

export interface LLMProvider {
  provider: string;
  name: string;
  description: string;
  models: string[];
  is_available: boolean;
}

export interface CreateModelRequest {
  name: string;
  provider: string;
  llm_model_id: string;
  api_key?: string;
  base_url?: string;
  max_tokens?: number;
  temperature?: number;
  is_active?: boolean;
}

export interface Conversation {
  id: number;
  user_id: number;
  title: string;
  llm_model_id: number;
  llm_model_name: string;
  provider: string;
  is_active: boolean;
  created_at: string;
  updated_at: string;
  message_count: number;
}

export interface CreateConversationRequest {
  title: string;
  llm_model_id: number;
}

export interface ChatMessage {
  id: number;
  conversation_id: number;
  role: 'user' | 'assistant';
  content: string;
  created_at: string;
}

export interface ConversationHistory {
  conversation: Conversation;
  messages: ChatMessage[];
}

export interface ChatRequest {
  conversation_id: number;
  message: string;
}

export interface ChatResponse {
  message: string;
  conversation_id: number;
  message_id: number;
}

export interface TokenUsageResponse {
  conversation_id: number;
  total_tokens: number;
  prompt_tokens: number;
  completion_tokens: number;
  estimated_cost: number;
}

export const llmApi = {
  // 提供商和模型管理
  getProviders: (): Promise<LLMProvider[]> =>
    apiClient.get('/llm/providers'),

  getModels: (): Promise<LLMModel[]> =>
    apiClient.get('/llm/models'),

  createModel: (data: CreateModelRequest): Promise<LLMModel> =>
    apiClient.post('/llm/models', data),

  autoCreateModelsFromEnv: (): Promise<{ message: string; created_models: string[] }> =>
    apiClient.post('/llm/models/auto-create-from-env'),

  // 对话管理
  getConversations: (skip?: number, limit?: number): Promise<Conversation[]> =>
    apiClient.get('/llm/conversations', { skip: skip || 0, limit: limit || 20 }),

  createConversation: (data: CreateConversationRequest): Promise<Conversation> =>
    apiClient.post('/llm/conversations', data),

  getConversationHistory: (conversationId: number): Promise<ConversationHistory> =>
    apiClient.get(`/llm/conversations/${conversationId}`),

  updateConversationTitle: (conversationId: number, title: string): Promise<{ message: string }> =>
    apiClient.put(`/llm/conversations/${conversationId}`, { title }),

  // 聊天功能
  sendMessage: (data: ChatRequest): Promise<ChatResponse> =>
    apiClient.post('/llm/chat', data),

  // 流式聊天（需要特殊处理）
  sendMessageStream: async (data: ChatRequest): Promise<ReadableStream<Uint8Array> | null> => {
    const authStore = JSON.parse(localStorage.getItem('auth-store') || '{}');
    const token = authStore?.state?.token;

    const response = await fetch('/api/v1/llm/chat/stream', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error('流式聊天请求失败');
    }

    return response.body;
  },

  // Token 使用情况
  getConversationTokens: (conversationId: number): Promise<TokenUsageResponse> =>
    apiClient.get(`/llm/conversations/${conversationId}/tokens`),
  
  // 删除对话
  deleteConversation: (conversationId: number): Promise<{ message: string }> =>
    apiClient.delete(`/llm/conversations/${conversationId}`),
};